package com.paul.sys.tools;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Stack;


public class UniqueKeyGenerator {
	private final static Generator instance = new Generator();
 
	public static String getKey(){
		return instance.get();
	}
	public static void main(String[] args) throws Exception{
		for (int i = 0; i < 199999; i++) {
			System.out.println(instance.get());
		}
	} //main//

}

class Generator {
	private static final Log log = LogFactory.getLog(Generator.class);

	private Date currentPrefix;
	private Stack stack;
	

	protected Generator() {

		stack = new Stack();

	}

	private String getPrefixString() {
		Date now = new Date();
		if(currentPrefix!=null && currentPrefix.after( now)){
			while(currentPrefix.after( now)){
				log.debug("prefix is valid ,current thread sleep ,wait for prefix overdue");
				try{
					Thread.currentThread().sleep(1000L);
				}catch(Exception e){
					log.debug("produce key ",e) ;
				}
				now = new Date();
			}
		}
		currentPrefix= now;
		return new SimpleDateFormat("yyMMddhhmmss").format(now);
	}

	private void produce() {
		log.debug("produce key ");
		String prefixStr = getPrefixString();
		for (int i = 99999; i > 0; i--) {
			String key = prefixStr + ( new DecimalFormat("000000").format((long)i));
			stack.push(key);
		}
	}

	protected String get() {
		if (stack.empty()) {
			log.debug("stack empty");
			produce();
		}
		return (String) stack.pop();
	}
}
